package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RoleResourceMapper roleResourceMapper;


    @Override
    public PageBean<RoleVo> query(RoleDto dto,int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<Role> roles = roleMapper.selectPage(dto);
        return PageBean.of(roles,RoleVo.class);
    }

    @Override
    public void add(RoleDto dto) {
        Role role = BeanUtil.toBean(dto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public Set<String> selectid(Long roleId) {
        Set<String> strings = roleResourceMapper.selectResourceNoByRoleId(roleId);
        return strings;
    }

    @Override
    @Transactional
    public void update(RoleDto dto) {
        Role role = BeanUtil.toBean(dto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);

        if (ObjectUtil.isNull(dto.getCheckedResourceNos())){
            return;
        }

        roleResourceMapper.deleteByRoleId(dto.getId());

        Arrays.stream(dto.getCheckedResourceNos()).forEach(resourceNo->{
            RoleResource roleResource = RoleResource.builder().roleId(dto.getId()).resourceNo(resourceNo).dataState("0").build();
            roleResourceMapper.insert(roleResource);
        });
    }

    @Override
    public void delete(Long roleIds) {
        roleMapper.deleteByPrimaryKey(roleIds);
        roleResourceMapper.deleteByRoleId(roleIds);
    }

    @Override
    public List<RoleVo> selectall() {
        List<Role> list = roleMapper.list();
        List<RoleVo> vos = BeanUtil.copyToList(list, RoleVo.class);
        return vos;
    }

    @Override
    public List<RoleVo> initrole() {
        List<Role> list = roleMapper.list();
        List<RoleVo> vos = BeanUtil.copyToList(list, RoleVo.class);
        return vos;
    }


}
